<?php
/**
 * Description: 设置考试项目
 * User: devforma
 * Date: 15/1/7
 * Time: 16:43
 */

class SetExam implements iController {
    
    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $uddb;

        if (empty($queryArgs['exam_id']) || !is_numeric($queryArgs['exam_id']))
            return genOutput(1000);
        
        $u = validateUser($queryArgs);
        if ($u === 0 || $u === 3)
            return genOutput(1000);

        $examDetailId = $queryArgs['exam_id'];
        $fieldName = $u === 2 ? 'guest_id' : 'user_id';
        $userId = $queryArgs[$fieldName];

        //获取考试项目信息
        $examInfo = $this->getExamDetailInfo($examDetailId);
        if (empty($examInfo)) {
            return genOutput(1000);
        }

        //获取该用户的plan_data
        $sql = "SELECT * FROM `{$uddb->userDPData}` WHERE `{$fieldName}`=:user";
        $userData = $uddb->getRow($sql, array(':user'=>$userId));
        if (empty($userData)) { //用户首次生成计划
            $sno = $this->getSno($userId); //生成学号
            $uddb->insert($uddb->userDPData,
                array("$fieldName" => $userId,
                    'create_time' => date('Y-m-d H:i:s'),
                    'user_sno' => $sno
                ));
            $position = $uddb->lastInsertId();
        } else {
            $sno = $userData->user_sno; //用户的学号
            $position = $userData->id; //第几个开启上岸计划
        }

        //处理plan_data中的知识点数据
        $userNotes = array();

        //之前已经设置过考试项目
        if (!empty($userData->note_info) && ($notesDataArray = unserialize($userData->note_info))) {
            foreach ($notesDataArray as $note) {
                if (is_object($note)) {
                    $userNotes[$note->id] = $note;
                }
            }
        }

        $notes = array();
        $noteInfo = getNotesByTestId($examInfo->exam_id);
        if (empty($noteInfo)) { //知识点数据为空则默认为国考的数据
            $noteInfo = getNotesByTestId(1126);
        }

        if (empty($noteInfo))
            return genOutput(1000);

        foreach ($noteInfo as $row) {
            $notes[] = array(
                'id' => $row->note_id,
                'accuracy' => isset($userNotes[$row->note_id]) ? $userNotes[$row->note_id]['accuracy'] : '0',
                'learned' => false
            );
        }

        //更新用户的plan_data表
        $dayBeforeExam = (strtotime($examInfo->exam_day) - strtotime(date('Y-m-d'))) / 3600 / 24;
        $uddb->update($uddb->userDPData,
            array('testarea_id' => $examInfo->exam_id,
                'note_info' => serialize($notes),
                'day_before_exam' => $dayBeforeExam
            ),
            array($fieldName => $userId)
        );

        //增加或更新考试项目介绍任务
        $sql = sprintf("SELECT `id` FROM `%s` WHERE mission_type=%d AND `{$fieldName}`=%d",
            $uddb->recentAvMission, 1, $userId);
        $introTaskId = $uddb->getVar($sql);

        $args = array('mission_title' => '我的上岸计划',
            'mission_type' => 1,
            'mission_content' => serialize(array(
                'position' => $position,
                'exam_id' => $examDetailId
            )),
            'mission_date' => date('Y-m-d H:i:s'),
            'mission_status' => '0'
        );
        if (!empty($introTaskId)) { //更新
            $uddb->update($uddb->recentAvMission, $args, array('id' => $introTaskId));
        } else {
            $args[$fieldName] = $userId;
            $uddb->insert($uddb->recentAvMission, $args);
        }

        //删除用户信息缓存
        $cacheKey = 'dp:func:getUserData'.$userId;
        cacheDelete($cacheKey);
        
        return genOutput(1, array(
            'position' => intval($position),
            'sno' => intval($sno)
        ));
    }


    /**
     * 生成用户的学号
     * @param int $userId 用户id
     * @return string 学号
     */
    private static function genSno($userId) {
        return substr(strval(time()), -7).substr('00000'.$userId, -3);
    }


    /**
     * 获取用户学号
     * @param int $userId 用户id
     * @return string
     */
    private function getSno($userId) {
        global $uddb;
        $sno = $uddb->getVar('SELECT `user_sno` FROM `user_social_info` WHERE `user_id`='.$userId);

        if (empty($sno)) {
            $sno = self::genSno($userId);

            $uddb->update('user_social_info', array('user_sno' => $sno), array('user_id' => $userId));
        }

        return $sno;
    }


    /**
     * 获取考试项目详情
     *
     * @param int $examDetailId 考试项目详情id
     * @return bool|object
     */
    private function getExamDetailInfo($examDetailId) {
        global $cmsdb;

        $cacheKey = 'func:getExamDetailInfo:'.$examDetailId;
        if (($examDetail = cacheGet($cacheKey)) == null) {
            $examDetail = $cmsdb->getRow('SELECT * FROM `data_exam_detail` WHERE `id`=:eid', array(':eid' => $examDetailId));

            if (empty($examDetail))
                return false;

            cacheAdd($cacheKey, $examDetail, 4*60*60);
        }

        return $examDetail;
    }
}
